/**
 * Copyright (c) 2018 软唐 All rights reserved.
 * <p>
 * https://www.softtown.cn
 * <p>
 * 版权所有，侵权必究！
 */

package com.softtown.modules.oss.cloud;


import com.softtown.common.exception.ErrorCode;
import com.softtown.common.exception.RenException;
import com.softtown.common.utils.Result;
import com.softtown.common.utils.SpringContextUtils;
import com.softtown.modules.oss.entity.SysOssFileEntity;
import com.softtown.modules.security.oauth2.TokenGenerator;
import com.softtown.modules.security.service.SysUserTokenService;
import com.softtown.modules.security.user.SecurityUser;
import com.softtown.modules.sys.service.SysParamsService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;

/**
 * 本地上传
 *
 * @author Ding Ya Yong
 */
public class LocalCloudStorageService extends AbstractCloudStorageService  {

    private static  SysUserTokenService sysUserTokenService;
    static {
        LocalCloudStorageService.sysUserTokenService = SpringContextUtils.getBean(SysUserTokenService.class);
    }

    public LocalCloudStorageService(CloudStorageConfig config) {
        this.config = config;
    }

    @Override
    public String upload(byte[] data, String path) {
        return upload(new ByteArrayInputStream(data), path);
    }

    @Override
    public String upload(InputStream inputStream, String path) {
        File file = new File(config.getLocalPath() + File.separator + path);
        try {
            FileUtils.copyToFile(inputStream, file);
        } catch (IOException e) {
            throw new RenException(ErrorCode.OSS_UPLOAD_FILE_ERROR, e, "");
        }
        return config.getLocalDomain() + "/" + path;
    }

    @Override
    public String uploadSuffix(byte[] data, String suffix) {
        return upload(data, getPath(config.getLocalPrefix(), suffix));
    }

    @Override
    public String uploadSuffix(InputStream inputStream, String suffix) {
        return upload(inputStream, getPath(config.getLocalPrefix(), suffix));
    }

    @Override
    public String getHeadUrl(String path) {
        String token ="";
        if(SecurityUser.getUser().getId() !=null){
            token =  sysUserTokenService.getToken(SecurityUser.getUser().getId());
        }else {
            Long userId = 1067246875800000001L;
            token =  sysUserTokenService.getToken(userId);
        }

        return config.getLocalDomain()+path+"?token="+token;

    }

    @Override
    public SysOssFileEntity getStsToken(String path) {
        return null;
    }

    @Override
    public void deleteFile(String path) {
        File file = new File(config.getLocalPath() + File.separator + path);
        file.delete();
    }
}
